package cn.qdhlm.collectservice.service;


import cn.qdhlm.collectservice.common.Constant;
import cn.qdhlm.collectservice.common.helper.ProtocolHelper;
import cn.qdhlm.collectservice.common.helper.RocketMqProducer;
import cn.qdhlm.collectservice.common.util.CodeUtil;
import cn.qdhlm.collectservice.common.util.ComUtil;
import cn.qdhlm.collectservice.common.util.JsonUtil;
import cn.qdhlm.collectservice.model.rocketmq.Command;
import cn.qdhlm.collectservice.model.rocketmq.OnlineRecord;
import cn.qdhlm.collectservice.model.rocketmq.TerminalData;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import lombok.extern.log4j.Log4j2;
import org.apache.rocketmq.client.producer.SendResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.Map;

/**
 * @Name: UtilityService
 * @Description: UtilityService
 * @Author: jiangcs
 */
@Log4j2
@Service
public class UtilityService {
    @Autowired
    private RocketMqProducer producer;

    /**
     * 解析数据 保存 mongodb
     *
     * @param varMap
     * @param collectStatus
     * @param terminalState
     * @param collectTime
     * @param iccid
     * @param version
     * @param signal
     * @param voltage
     * @param moduleTime
     * @return
     */
    public boolean sendTerminalData(TerminalData terminalData, Map<String, Object> varMap, int collectStatus, String terminalState, String collectTime, String iccid
            , int version, int signal, double voltage, String moduleTime) {

        terminalData.setVarMap(varMap);
        terminalData.setCollectStatus(collectStatus);
        terminalData.setTerminalState(terminalState);
        terminalData.setCollectTime(collectTime);

        terminalData.setIccid(iccid);
        terminalData.setVersion(version);
        terminalData.setNetwork(3);
        terminalData.setSignal(signal);
        terminalData.setVoltage(voltage);
        terminalData.setModuleTime(moduleTime);

//        terminalData.setTerminalId(terminalVO.getId());
//        terminalData.setTerminalNo(terminalNo);
//        terminalData.setTerminalType(terminalType);
//        terminalData.setTerminalLevel(terminalVO.getLevel());
//        terminalData.setMacAddr(macAddr);
//        terminalData.setCustomerId(terminalVO.getCustomerId());
//        terminalData.setHouseholdId(terminalVO.getHouseholdId());
//        terminalData.setHeatState(terminalVO.getHeatState());
//        terminalData.setProtocolCode(protocolCode);

        terminalData.setStatus(0);
        terminalData.setCreateTime(new Date());
        System.out.println(terminalData);
        try {
            /**
             * 发送主题 TerminalData 负责推送的springboot接受
             */
            producer.send(Constant.ROCKETMQ_TOPIC_TERMINALDATA, Constant.ROCKETMQ_TAG, JsonUtil.safeJsonStr(terminalData).getBytes(StandardCharsets.UTF_8));

            /**
             * 发送主题 OnlineData
             */
            sendOnlineRecord(terminalData.getTerminalNo(),iccid, null, terminalData.getMacAddr(), terminalData.getNetwork(), signal, voltage, version, moduleTime);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    private void sendOnlineRecord(String terminalNo, String iccId, String iMei, String macAddr, Integer network, Integer signal, double voltage, Integer version, String moduleTime) {
        OnlineRecord onlineRecord = new OnlineRecord();
        onlineRecord.setTerminalNo(terminalNo);
        onlineRecord.setIccId(iccId);
        onlineRecord.setCreateTime(new Date());
        onlineRecord.setIMei(iMei);
        onlineRecord.setMacAddr(macAddr);
        onlineRecord.setNetwork(network);
        onlineRecord.setSignal(signal);
        onlineRecord.setVoltage(voltage);
        onlineRecord.setVersion(version);
        onlineRecord.setModuleTime(moduleTime);
        // 终端在线了
        onlineRecord.setTerminalOnline(true);
        /**
         * 发布主题 OnlineData 负责推送的springboot接受
         */
        producer.send(Constant.ROCKETMQ_TOPIC_ONLINEDATA, Constant.ROCKETMQ_TAG, JsonUtil.safeJsonBytes(onlineRecord));

        /**
         * 发送主题 nb-is-on 负责发送命令的springboot接受
         */
        producer.send(Constant.ROCKETMQ_TOPIC_NBISON, "nb-is-on", JsonUtil.safeJsonBytes(onlineRecord));
    }


    public SendResult sendCommand(String terminalNo,Integer nextSn, String macAddr, Integer codeCustomNb, String funcCode, ByteBuf byteBuf) {
        Command command = new Command();
        command.setTerminalNo(terminalNo);
        command.setMacAddr(macAddr);
        command.setCodeCustomNb(codeCustomNb);
        command.setFuncCode(funcCode);
        command.setData(CodeUtil.hexStringToBase64String(ByteBufUtil.hexDump(byteBuf)));
//        command.setCommandTerminalId(commandTerminalId);
        command.setNextSn(nextSn);
        command.setCreateTime(new Date());
        /**
         * 发送主题 Command 负责发送命令的springboot接受
         */
        SendResult sendResult = producer.send(Constant.ROCKETMQ_TOPIC_COMMAND, Constant.ROCKETMQ_TAG, JsonUtil.safeJsonStr(command).getBytes(StandardCharsets.UTF_8));
        log.info("send command ok: {}", JsonUtil.safeJsonStr(command));
        // 存入mongodb
//        MongoHelper.save(command);
        return sendResult;
    }

    /**
     * 更新 command result & status
     *
     * @param terminalNo
     * @param sn
     * @param resultMap
     * @param status
     */
/*    public void updateCommandResultAndStatus(String terminalNo, int sn, Map<String, Object> resultMap, int status) {
        // 结果转换处理
        String result = JsonUtil.safeJsonStr(resultMap);
        String resultZH = JsonUtil.safeJsonStr(convert2zh(resultMap));

        Integer id = commandTerminalMapper.getIdByTerminalNoAndSnAndStatus(terminalNo, sn, 1);
        if (id != null) {
            int count = commandTerminalMapper.updateResultStatus(id, result, resultZH, status);
            if (count <= 0) {
                log.error("updateCommandTerminalStatus: commandTerminalMapper.updateStatus fail");
            }
        } else {
            log.error("updateCommandTerminalStatus: commandTerminalMapper.get terminalNo[{}],sn[{}],status[{}] fail", terminalNo, sn, status);
        }
    }*/

    /**
     * 结果 关键字 转换
     *
     * @param resultMap
     * @return
     */
//    private Map<String, Object> convert2zh(Map<String, Object> resultMap) {
//        Map<String, Object> resultZHMap;
//        if (null == resultMap) {
//            return null;
//        }
//        resultZHMap = new HashMap<>(resultMap.size());
//
//        for (String key : resultMap.keySet()) {
//            switch (key) {
//                case "statusCode":
//                    resultZHMap.put("状态码", resultMap.get(key));
//                    break;
//                case "macAddr":
//                    resultZHMap.put("终端地址", resultMap.get(key));
//                    break;
//                case "ip":
//                    resultZHMap.put("IP地址", resultMap.get(key));
//                    break;
//                case "port":
//                    resultZHMap.put("端口", resultMap.get(key));
//                    break;
//                case "moduleTime":
//                    resultZHMap.put("模组时间", resultMap.get(key));
//                    break;
//                case "uploadMode":
//                    String uploadModeTxt;
//                    int uploadMode = ComUtil.safeInt(resultMap.get(key));
//                    switch (uploadMode) {
//                        case 0:
//                            uploadModeTxt = "采后传";
//                            break;
//                        case 1:
//                            uploadModeTxt = "时段传";
//                            break;
//                        default:
//                            uploadModeTxt = "未知";
//                    }
//                    resultZHMap.put("上传模式", uploadModeTxt);
//                case "startTime":
//                    resultZHMap.put("上传开始时间", resultMap.get(key));
//                    break;
//                case "endTime":
//                    resultZHMap.put("上传结束时间", resultMap.get(key));
//                    break;
//                case "collectMode":
//                    String collectModeTxt;
//                    int collectMode = ComUtil.safeInt(resultMap.get(key));
//                    switch (collectMode) {
//                        case 0:
//                            collectModeTxt = "周期";
//                            break;
//                        case 1:
//                            collectModeTxt = "定时";
//                            break;
//                        default:
//                            collectModeTxt = "未知";
//                    }
//                    resultZHMap.put("采集模式", collectModeTxt);
//                    break;
//                case "interval":
//                    resultZHMap.put("采集间隔", resultMap.get(key));
//                    break;
//                case "time1":
//                    resultZHMap.put("定时时间1", resultMap.get(key));
//                    break;
//                case "time2":
//                    resultZHMap.put("定时时间2", resultMap.get(key));
//                    break;
//                case "codeCustomNb":
//                    resultZHMap.put("客户协议编码", resultMap.get(key));
//                    break;
//                case "signal":
//                    resultZHMap.put("信号", resultMap.get(key));
//                    break;
//                case "iccid":
//                    resultZHMap.put("iccid", resultMap.get(key));
//                    break;
//                case "state":
//                    resultZHMap.put("状态字", resultMap.get(key));
//                    break;
//                case "cleanCycle":
//                    resultZHMap.put("清洗周期(时)", resultMap.get(key));
//                    break;
//                case "heatSeasonStart":
//                    resultZHMap.put("采暖季开始", resultMap.get(key));
//                    break;
//                case "heatSeasonEnd":
//                    resultZHMap.put("采暖季结束", resultMap.get(key));
//                    break;
//                case "openDegreeUpper":
//                    resultZHMap.put("开度上限", resultMap.get(key));
//                    break;
//                case "openDegreeLower":
//                    resultZHMap.put("开度下限", resultMap.get(key));
//                    break;
//                case "adjustMode":
//                    String adjustModeTxt;
//                    int adjustMode = ComUtil.safeInt(resultMap.get(key));
//                    switch (adjustMode) {
//                        case 0:
//                            adjustModeTxt = "面板控制";
//                            break;
//                        case 1:
//                            adjustModeTxt = "远程控制开度";
//                            break;
//                        case 2:
//                            adjustModeTxt = "回水温度控制开度";
//                            break;
//                        case 3:
//                            adjustModeTxt = "进回水温差控制开度";
//                            break;
//                        default:
//                            adjustModeTxt = "未知";
//                    }
//                    resultZHMap.put("调节模式", adjustModeTxt);
//                    break;
//                case "autoAdjust":
//                    String autoAdjustTxt;
//                    int autoAdjust = ComUtil.safeInt(resultMap.get(key));
//                    switch (autoAdjust) {
//                        case 0:
//                            autoAdjustTxt = "启用";
//                            break;
//                        case 1:
//                            autoAdjustTxt = "不启用";
//                            break;
//                        default:
//                            autoAdjustTxt = "未知";
//                    }
//                    resultZHMap.put("是否启用自动调平", autoAdjustTxt);
//                    break;
//                case "adjustValue":
//                    resultZHMap.put("目标调节值", resultMap.get(key));
//                    break;
//                case "adjustCycle":
//                    resultZHMap.put("调节周期(分)", resultMap.get(key));
//                    break;
//                case "adjustDeadZone":
//                    resultZHMap.put("调节死区", resultMap.get(key));
//                    break;
//                case "coefficientP":
//                    resultZHMap.put("系数P", resultMap.get(key));
//                    break;
//                case "coefficientI":
//                    resultZHMap.put("系数I", resultMap.get(key));
//                    break;
//                case "coefficientD":
//                    resultZHMap.put("系数D", resultMap.get(key));
//                    break;
//                case "adjustRatio":
//                    resultZHMap.put("调节比例", resultMap.get(key));
//                    break;
//                case "startDate":
//                    resultZHMap.put("开启计量日期", resultMap.get(key));
//                    break;
//                case "endDate":
//                    resultZHMap.put("结束计量日期", resultMap.get(key));
//                    break;
//                case "controlMode":
//                    String controlModeTxt;
//                    int controlMode = ComUtil.safeInt(resultMap.get(key));
//                    switch (controlMode) {
//                        case 0:
//                            controlModeTxt = "充值时间段启作用";
//                            break;
//                        case 1:
//                            controlModeTxt = "充值小时启作用";
//                            break;
//                        default:
//                            controlModeTxt = "未知";
//                    }
//                    resultZHMap.put("充值控制模式", controlModeTxt);
//                    break;
//                case "controlSerialNo":
//                    resultZHMap.put("充值流水号", resultMap.get(key));
//                    break;
//                case "controlDateStart":
//                    resultZHMap.put("充值时间段开始", resultMap.get(key));
//                    break;
//                case "controlDateEnd":
//                    resultZHMap.put("充值时间段结束", resultMap.get(key));
//                    break;
//                case "controlAvailableTime":
//                    resultZHMap.put("充值小时", resultMap.get(key));
//                    break;
//                case "temperatureDiff":
//                    resultZHMap.put("温度偏差", resultMap.get(key));
//                    break;
//                case "rechargeRecordList":
//                    resultZHMap.put("充值记录列表", resultMap.get(key));
//                    break;
//                default:
//                    log.error("convert2zh: key[{}] match failed", key);
//            }
//        }
//        return resultZHMap;
//    }

    /**
     * 调节阀：保存 终端配置参数
     *
     * @param terminalId
     * @param paramMap
     */
/*    public void saveTerminalNBConfigParam4Adjust(Integer terminalId, Map<String, Object> paramMap) {
        try {
            int count;

            Integer id = configParamTerminalNBMapper.getIdByTerminalId(terminalId);
            if (id == null) {
                // 终端Id
                paramMap.put("terminalId", terminalId);
                count = configParamTerminalNBMapper.insert4Adjust(paramMap);
                if (count <= 0) {
                    log.error("terminal_nb[adjust] config param insert fail");
                    return;
                }
            } else {
                // 记录Id
                paramMap.put("id", id);
                count = configParamTerminalNBMapper.update4Adjust(paramMap);
                if (count <= 0) {
                    log.error("adjust terminal_nb[adjust] config param update fail");
                    return;
                }
            }
            log.info("terminal_nb[adjust] config param save ok: {}", JsonUtil.safeJsonStr(paramMap));
        } catch (Exception e) {
            log.error("terminal_nb[adjust] config param save exception", e);
        }
    }*/

    /**
     * 调节阀：保存 终端配置参数
     *
     * @param terminalId
     * @param protocolCode
     * @param paramMap
     */
    /*public void saveTerminalNBConfigParam4Adjust(Integer terminalId, String protocolCode, Map<String, Object> paramMap) {
        try {
            int count;

            Integer id = configParamTerminalNBMapper.getIdByTerminalId(terminalId);
            if (id == null) {
                // 终端Id
                paramMap.put("terminalId", terminalId);
                count = configParamTerminalNBMapper.insert4Adjust(paramMap);
                if (count <= 0) {
                    log.error("terminal_nb[adjust-{}] config param insert fail", protocolCode);
                    return;
                }
            } else {
                // 记录Id
                paramMap.put("id", id);
                count = configParamTerminalNBMapper.update4Adjust(paramMap);
                if (count <= 0) {
                    log.error("adjust terminal_nb[adjust-{}] config param update fail", protocolCode);
                    return;
                }
            }
            log.info("terminal_nb[adjust-{}] config param save ok: {}", protocolCode, JsonUtil.safeJsonStr(paramMap));
        } catch (Exception e) {
            log.error("terminal_nb[adjust-{}] config param save exception", protocolCode, e);
        }
    }*/

    /**
     * 锁闭阀：保存 终端配置参数
     *
     * @param terminalId
     * @param paramMap
     */
   /* public void saveTerminalNBConfigParam4Lock(Integer terminalId, Map<String, Object> paramMap) {
        try {
            int count;

            Integer id = configParamTerminalNBMapper.getIdByTerminalId(terminalId);
            if (id == null) {
                // 终端Id
                paramMap.put("terminalId", terminalId);
                count = configParamTerminalNBMapper.insert4Lock(paramMap);
                if (count <= 0) {
                    log.error("terminal_nb[lock] config param insert fail");
                    return;
                }
            } else {
                // 记录Id
                paramMap.put("id", id);
                count = configParamTerminalNBMapper.update4Lock(paramMap);
                if (count <= 0) {
                    log.error("terminal_nb[lock] config param update fail");
                    return;
                }
            }
            log.info("terminal_nb[lock] config param save ok: {}", JsonUtil.safeJsonStr(paramMap));
        } catch (Exception e) {
            log.error("terminal_nb[lock] config param save exception", e);
        }
    }*/

    /**
     * 锁闭阀：保存 终端配置参数
     *
     * @param terminalId
     * @param protocolCode
     * @param paramMap
     */
   /* public void saveTerminalNBConfigParam4LockWAC550(Integer terminalId, String protocolCode, Map<String, Object> paramMap) {
        try {
            int count;

            Integer id = configParamTerminalNBMapper.getIdByTerminalId(terminalId);
            if (id == null) {
                // 终端Id
                paramMap.put("terminalId", terminalId);
                count = configParamTerminalNBMapper.insert4Lock(paramMap);
                if (count <= 0) {
                    log.error("terminal_nb[lock-{}] config param insert fail", protocolCode);
                    return;
                }
            } else {
                // 记录Id
                paramMap.put("id", id);
                count = configParamTerminalNBMapper.update4Lock(paramMap);
                if (count <= 0) {
                    log.error("terminal_nb[lock-{}] config param update fail", protocolCode);
                    return;
                }
            }
            log.info("terminal_nb[lock-{}] config param save ok: {}", protocolCode, JsonUtil.safeJsonStr(paramMap));
        } catch (Exception e) {
            log.error("terminal_nb[lock-{}] config param save exception", protocolCode, e);
        }
    }*/

    /**
     * 采暖季：保存 终端配置参数
     *
     * @param terminalId
     * @param paramMap
     */
    /*public void saveTerminalNBConfigParam4HeatSeason(Integer terminalId, Map<String, Object> paramMap) {
        try {
            int count;

            Integer id = configParamTerminalNBMapper.getIdByTerminalId(terminalId);
            if (id == null) {
                // 终端Id
                paramMap.put("terminalId", terminalId);
                count = configParamTerminalNBMapper.insert4HeatSeason(paramMap);
                if (count <= 0) {
                    log.error("terminal_nb[heatSeason] config param insert fail");
                    return;
                }
            } else {
                // 记录Id
                paramMap.put("id", id);
                count = configParamTerminalNBMapper.update4HeatSeason(paramMap);
                if (count <= 0) {
                    log.error("terminal_nb[heatSeason] config param update fail");
                    return;
                }
            }
            log.info("terminal_nb[heatSeason] config param save ok: {}", JsonUtil.safeJsonStr(paramMap));
        } catch (Exception e) {
            log.error("terminal_nb[heatSeason] config param save exception", e);
        }
    }*/

    /**
     * 获取 命令名称
     *
     * @param afn
     * @param fn
     * @param protocolCode
     * @return
     */
    public String getCmdOperation(String afn, String fn, String protocolCode) {
        String operation;
        switch (afn) {
            // 设置命令
            case "03":
                switch (fn) {
                    case "1":
                        operation = "设置服务器1信息";
                        break;
                    case "3":
                        operation = "校时";
                        break;
                    case "4":
                        operation = "设置上传模式";
                        break;
                    case "5":
                        operation = "设置采集模式";
                        break;
                    case "6":
                        operation = "设置表信息";
                        break;
                    case "31":
                        operation = "温湿度修正";
                        break;
                    case "32":
                        operation = "温度修正";
                        break;
                    case "250":
                        operation = "测量点配置下发";
                        break;
                    case "251":
                        operation = "测量点全部信息";
                        break;
                    case "254":
                        operation = "配置下发";
                        break;
                    case "255":
                        operation = "设置全部信息2";
                        break;
                    default:
                        operation = "未知";
                }
                break;
            // 查询参数
            case "05":
                switch (fn) {
                    case "1":
                        operation = "设置服务器1信息";
                        break;
                    case "3":
                        operation = "校时";
                        break;
                    case "4":
                        operation = "设置上传模式";
                        break;
                    case "5":
                        operation = "设置采集模式";
                        break;
                    case "6":
                        operation = "设置表信息";
                        break;
                    case "7":
                        operation = "查询信号";
                        break;
                    case "8":
                        operation = "查询ICCID";
                        break;
                    case "9":
                        operation = "查询程序版本";
                        break;
                    case "255":
                        operation = "设置全部信息2";
                        break;
                    default:
                        operation = "未知";
                }
                break;
            // 1类数据
            case "0a":
                switch (fn) {
                    case "1":
                        operation = "透传数据";
                        break;
                    default:
                        operation = "未知";
                }
                break;
            // 控制
            case "0c":
                switch (fn) {
                    case "1":
                        operation = "读取阀门数据";
                        break;
                    case "2":
                        operation = "休眠";
                        break;
                    case "3":
                        operation = "强制设温";
                        break;
                    case "4":
                        operation = "解锁";
                        break;
                    case "5":
                        operation = "写累计工作时间";
                        break;
                    case "6":
                        operation = "写供暖期";
                        break;
                    case "7":
                        operation = "读供暖期";
                        break;
                    case "55":
                        operation = "强制开阀门";
                        break;
                    case "66":
                        operation = "普通开阀门";
                        break;
                    case "77":
                        operation = "普通关阀门";
                        break;
                    case "88":
                        operation = "阀门清洗";
                        break;
                    case "99":
                        operation = "强制关阀门";
                        break;
                    case "ff":
                        operation = "自由控制";
                        break;
                    case "ac03":
                        operation = "是否启用温差、回温调节";
                        break;
                    case "ac04":
                        operation = "写目标调节值";
                        break;
                    case "a028":
                        operation = "写阀门开度上下限";
                        break;
                    case "ac01":
                        if ("EN1434_9988".equals(protocolCode)) {
                            operation = "设置温度偏差";
                        } else {
                            operation = "写阀门所有配置参数";
                        }
                        break;
                    case "ab01":
                        if ("EN1434_9988".equals(protocolCode)) {
                            operation = "读温度偏差";
                        } else {
                            operation = "读调节阀所有配置参数";
                        }
                        break;
                    case "a02c":
                        operation = "写清洗阀门周期";
                        break;
                    case "a02d":
                        operation = "读清洗阀门周期";
                        break;
                    case "ac05":
                        operation = "写充值信息";
                        break;
                    case "ab05":
                        operation = "读充值信息";
                        break;
                    case "ac07":
                        operation = "充值信息清除";
                        break;
                    case "a101":
                        operation = "写充值水量信息";
                        break;
                    case "a201":
                        operation = "查询水量充值记录";
                        break;
                    case "a102":
                        operation = "撤销某次水量充值";
                        break;
                    case "1020":
                        operation = "管理卡";
                        break;
                    default:
                        operation = "未知";
                }
                break;
            default:
                operation = "未知";
        }
        return operation;
    }

    /**
     * 获取 终端通讯标识：
     * 组合规则：
     * <p>
     * modbus：协议类型 + 协议编码首字母 + 协议编码后两位数字 + 采集器编码10位 + 终端地址后2位
     * common：协议类型 + 协议编码首字母 + 协议编码后两位数字 + 终端地址后12位（不足前补0）
     *
     * @param type
     * @param protocolCode
     * @param collectorNo
     * @param macAddr
     * @return
     */
    public String getTerminalNo(Integer type, String protocolCode, String collectorNo, String macAddr) {
        String terminalNo = type + protocolCode.substring(0, 1) + protocolCode.substring(protocolCode.length() - 2);
        // modbus规则
        if (protocolCode.startsWith(Constant.PROTOCOL_PREFIX_MODBUS)) {
            if (collectorNo != null && collectorNo.length() < Constant.LENGTH_COLLECTOR_NO) {
                collectorNo = ComUtil.fillZeroLeft(collectorNo, Constant.LENGTH_COLLECTOR_NO);
            }
            if (macAddr.length() < Constant.LENGTH_TERMINAL_MAC_ADDR_MODBUS) {
                macAddr = ComUtil.fillZeroLeft(macAddr, Constant.LENGTH_TERMINAL_MAC_ADDR_MODBUS);
            }
            terminalNo += collectorNo + macAddr.substring(macAddr.length() - Constant.LENGTH_TERMINAL_MAC_ADDR_MODBUS);
        }
        // 通用规则
        else {
            if (macAddr.length() < (Constant.LENGTH_TERMINAL_MAC_ADDR - 2)) {
                macAddr = ComUtil.fillZeroLeft(macAddr, (Constant.LENGTH_TERMINAL_MAC_ADDR - 2));
            }
            terminalNo += macAddr.substring(macAddr.length() - (Constant.LENGTH_TERMINAL_MAC_ADDR - 2));
        }
        return terminalNo;
    }

    public Integer getProtocolType(String protocolCode) {


        try {
            // 协议code
            boolean existFlag = ProtocolHelper.exists(protocolCode);
            if (!existFlag) {
                throw new RuntimeException("ini.protocolCode[" + protocolCode + "] not exists");
            }

            // 协议文件参数：info
            Map<String, Object> paramInfoMap = ProtocolHelper.getParameterMap(protocolCode, "info");
            if (paramInfoMap == null) {
                throw new RuntimeException("ini.protocolCode[" + protocolCode + "].parameter.info not exists");
            }

            return ComUtil.safeInt(paramInfoMap.get("protocoltype"));
        } catch (Exception e) {
            log.error("verify terminal exception: {}", e.getMessage());
            return null;
        }
    }

    // TODO: 2020/12/8 协议编码和 codeCustomNb映射 要放到配置文件中
    public String getProtocolCode(int codeCustomNb) {
        try {
            if (codeCustomNb == 1) {
                return "CJT188_0100";
            } else if (codeCustomNb == 11) {
                return "CJT188_0060";
            } else if (codeCustomNb == 12) {
                return "CJT188_0061";
            } else if (codeCustomNb == 255) {
                return "CJT188_0064";
            } else if (codeCustomNb == 4) {
                return "CJT188_0033";
            } else if (codeCustomNb == 5) {
                return "CJT188_0046";
            } else if (codeCustomNb == 70) {
                return "EN1434_9994";
            } else if (codeCustomNb == 71) {
                return "EN1434_9993";
            } else if (codeCustomNb == 72) {
                return "EN1434_9992";
            } else if (codeCustomNb == 73) {
                return "EN1434_9988";
            } else if (codeCustomNb == 74) {
                return "EN1434_0044";
            } else if (codeCustomNb == 75) {
                return "EN1434_9983";
            } else if (codeCustomNb == 80) {
                return "EN1434_9985";
            } else if (codeCustomNb == 82) {
                return "EN1434_9982";
            } else if (codeCustomNb == 84) {
                return "EN1434_0062";
            } else if (codeCustomNb == 85) {
                return "EN1434_0065";
            } else if (codeCustomNb == 86) {
                return "EN1434_9981";
            } else if (codeCustomNb == 87) {
                return "EN1434_0066";
            } else if (codeCustomNb == 88) {
                return "EN1434_9980";
            } else if (codeCustomNb == 9) {
                return "CJT188_0053";
            } else if (codeCustomNb == 90) {
                return "EN1434_0063";
            }
            return "";
        } catch (Exception e) {
            log.error("verify protocol exception: {}", e.getMessage());
            return null;
        }
    }

    /**
     * 通知调用
     *
     * @param exNBTerminalData
     */
    /*public void notifyInvoke(ExNBTerminalData exNBTerminalData) {
        ThreadPoolHelper.getCachedInstance().execute(() -> {
            String allChildIdStr;

            Map<String, Object> varMap = exNBTerminalData.getVarMap();

            // 中自沣泰：调节阀，05
            if (PropertyValue.NOTIFY_FENGTAI) {
                allChildIdStr = customerMapper.getAllChildIdByName(Constant.CUSTOMER_FENG_TAI);
                if (ComUtil.isContain(allChildIdStr, exNBTerminalData.getCustomerId())) {
                    Map<String, Object> dataMap = new HashMap<>(4);
                    dataMap.put("macAddr", exNBTerminalData.getMacAddr());
                    dataMap.put("customerTxt", exNBTerminalData.getCustomerTxt());
                    dataMap.put("temperature", varMap.get("05"));
                    dataMap.put("collectTime", exNBTerminalData.getCollectTime());

                    RedisHelper.send("fengtai/data-change", JsonUtil.safeJsonStr(dataMap));

                    log.info("notifyInvoke fengtai ok: data[{}]", JsonUtil.safeJsonStr(dataMap));
                    return;
                }
            }

            // 天津兆鸿自动化：测温插座，04
            if (PropertyValue.NOTIFY_ZHAOHONG) {
                allChildIdStr = customerMapper.getAllChildIdByName(Constant.CUSTOMER_ZHAO_HONG);
                if (ComUtil.isContain(allChildIdStr, exNBTerminalData.getCustomerId())) {
                    Map<String, Object> dataMap = new HashMap<>(5);
                    dataMap.put("macAddr", exNBTerminalData.getMacAddr());
                    dataMap.put("customerTxt", exNBTerminalData.getCustomerTxt());
                    dataMap.put("temperature", varMap.get("04"));
                    dataMap.put("collectTime", exNBTerminalData.getCollectTime());
                    // sim信号
                    dataMap.put("simSignal", onlineTerminalMapper.getRecentSimSignal(exNBTerminalData.getTerminalNo()));

                    RedisHelper.send("zhaohong/data-change", JsonUtil.safeJsonStr(dataMap));

                    log.info("notifyInvoke zhaohong ok: data[{}]", JsonUtil.safeJsonStr(dataMap));
                }
            }
        });
    }*/
}
